<template>
  <div class="cross-organization-analysis">
    <!-- 页面标题 -->
    <PageHeader 
      title="跨组织分析" 
      description="查看和分析多个组织的业务数据"
      icon="DataLine"
    />
    
    <!-- 组织选择器 -->
    <el-card class="org-selector-card" shadow="never">
      <div class="org-selector">
        <el-select 
          v-model="selectedOrgIds" 
          multiple 
          placeholder="请选择要分析的组织"
          style="width: 100%"
        >
          <el-option
            v-for="org in userOrganizations"
            :key="org.id"
            :label="org.name"
            :value="org.id"
          />
        </el-select>
        <el-button 
          type="primary" 
          @click="loadAnalysisData"
          :disabled="selectedOrgIds.length === 0"
          style="margin-left: 15px"
        >
          开始分析
        </el-button>
      </div>
    </el-card>
    
    <!-- 分析结果 -->
    <div v-if="analysisData" class="analysis-results">
      <!-- 客户分析 -->
      <el-card class="analysis-card" shadow="never">
        <template #header>
          <div class="card-header">
            <el-icon><User /></el-icon>
            <span>客户分析</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <div ref="customerDistributionChart" class="chart-container"></div>
          </el-col>
          <el-col :span="16">
            <div ref="revenueTrendChart" class="chart-container"></div>
          </el-col>
        </el-row>
      </el-card>
      
      <!-- 销售分析 -->
      <el-card class="analysis-card" shadow="never">
        <template #header>
          <div class="card-header">
            <el-icon><TrendCharts /></el-icon>
            <span>销售分析</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="16">
            <div ref="salesTrendChart" class="chart-container"></div>
          </el-col>
          <el-col :span="8">
            <div ref="topProductsChart" class="chart-container"></div>
          </el-col>
        </el-row>
      </el-card>
      
      <!-- 财务分析 -->
      <el-card class="analysis-card" shadow="never">
        <template #header>
          <div class="card-header">
            <el-icon><Money /></el-icon>
            <span>财务分析</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="16">
            <div ref="financialTrendChart" class="chart-container"></div>
          </el-col>
          <el-col :span="8">
            <div ref="expenseDistributionChart" class="chart-container"></div>
          </el-col>
        </el-row>
      </el-card>
      
      <!-- 供应商分析 -->
      <el-card class="analysis-card" shadow="never">
        <template #header>
          <div class="card-header">
            <el-icon><OfficeBuilding /></el-icon>
            <span>供应商分析</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div ref="supplierDistributionChart" class="chart-container"></div>
          </el-col>
          <el-col :span="12">
            <div ref="supplierStatusChart" class="chart-container"></div>
          </el-col>
        </el-row>
      </el-card>
    </div>
    
    <!-- 加载状态 -->
    <div v-else-if="loading" class="loading-container">
      <el-skeleton animated />
    </div>
    
    <!-- 空状态 -->
    <div v-else class="empty-container">
      <el-empty description="请选择要分析的组织">
        <el-button type="primary" @click="loadUserOrganizations">刷新组织列表</el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup lang="ts">
// @ts-nocheck
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  User, TrendCharts, Money, OfficeBuilding
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import PageHeader from '@/components/layout/PageHeader.vue'
import { organizationAPI } from '@/api/organization'
import { analysisAPI } from '@/api/analysis'

// 响应式数据
const userOrganizations = ref([])
const selectedOrgIds = ref([])
const analysisData = ref(null)
const loading = ref(false)

// 图表实例
let customerDistributionChartInstance = null
let revenueTrendChartInstance = null
let salesTrendChartInstance = null
let topProductsChartInstance = null
let financialTrendChartInstance = null
let expenseDistributionChartInstance = null
let supplierDistributionChartInstance = null
let supplierStatusChartInstance = null

// 图表DOM引用
const customerDistributionChart = ref(null)
const revenueTrendChart = ref(null)
const salesTrendChart = ref(null)
const topProductsChart = ref(null)
const financialTrendChart = ref(null)
const expenseDistributionChart = ref(null)
const supplierDistributionChart = ref(null)
const supplierStatusChart = ref(null)

// 获取用户所属的组织
const loadUserOrganizations = async () => {
  try {
    // 检查是否有token
    const token = localStorage.getItem('token');
    if (!token) {
      ElMessage.warning('请先登录系统');
      return;
    }
    
    // 添加调试信息
    console.log('当前token:', token);
    
    const response = await organizationAPI.getUserOrganizations();
    if (response.success) {
      userOrganizations.value = response.data;
    } else {
      ElMessage.error(response.message || '获取组织列表失败');
    }
  } catch (error) {
    console.error('获取用户组织失败:', error);
    ElMessage.error('获取组织列表失败: ' + (error as Error).message);
  }
};

// 加载分析数据
const loadAnalysisData = async () => {
  if (selectedOrgIds.value.length === 0) {
    ElMessage.warning('请至少选择一个组织')
    return
  }
  
  loading.value = true
  try {
    const response = await analysisAPI.getCrossOrganizationAnalysis({
      organizationIds: selectedOrgIds.value
    })
    
    if (response.success) {
      analysisData.value = response.data
      await nextTick()
      updateAllCharts()
    } else {
      ElMessage.error(response.message || '获取分析数据失败')
    }
  } catch (error) {
    console.error('获取分析数据失败:', error)
    ElMessage.error('获取分析数据失败')
  } finally {
    loading.value = false
  }
}

// 更新所有图表
const updateAllCharts = () => {
  if (!analysisData.value) return
  
  updateCustomerCharts(analysisData.value.charts)
  updateSalesCharts(analysisData.value.charts)
  updateFinancialCharts(analysisData.value.charts)
  updateSupplierCharts(analysisData.value.charts)
}

// 更新客户图表
const updateCustomerCharts = (chartsData: any) => {
  // 客户分布饼图
  if (customerDistributionChart.value) {
    // 确保DOM元素已渲染并有尺寸
    if (customerDistributionChart.value.clientWidth > 0 && customerDistributionChart.value.clientHeight > 0) {
      if (!customerDistributionChartInstance) {
        customerDistributionChartInstance = echarts.init(customerDistributionChart.value)
      }
      
      const option = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          top: '5%',
          left: 'center'
        },
        series: [
          {
            name: '客户分布',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: chartsData.customerDistribution
          }
        ]
      }
      
      customerDistributionChartInstance.setOption(option, true)
    }
  }
  
  // 收入趋势柱状图
  if (revenueTrendChart.value) {
    // 确保DOM元素已渲染并有尺寸
    if (revenueTrendChart.value.clientWidth > 0 && revenueTrendChart.value.clientHeight > 0) {
      if (!revenueTrendChartInstance) {
        revenueTrendChartInstance = echarts.init(revenueTrendChart.value)
      }
      
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: chartsData.revenueTrend.map((item: any) => item.name)
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '收入',
            type: 'bar',
            data: chartsData.revenueTrend.map((item: any) => item.value),
            itemStyle: {
              color: '#e6a23c'
            }
          }
        ]
      }
      
      revenueTrendChartInstance.setOption(option, true)
    }
  }
}

// 更新销售图表
const updateSalesCharts = (chartsData: any) => {
  // 销售趋势柱状图
  if (salesTrendChart.value) {
    // 确保DOM元素已渲染并有尺寸
    if (salesTrendChart.value.clientWidth > 0 && salesTrendChart.value.clientHeight > 0) {
      if (!salesTrendChartInstance) {
        salesTrendChartInstance = echarts.init(salesTrendChart.value)
      }
      
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: chartsData.salesTrend.map((item: any) => item.name)
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '销售额',
            type: 'bar',
            data: chartsData.salesTrend.map((item: any) => item.value),
            itemStyle: {
              color: '#67c23a'
            }
          }
        ]
      }
      
      salesTrendChartInstance.setOption(option, true)
    }
  }
  
  // 热门产品饼图
  if (topProductsChart.value) {
    // 确保DOM元素已渲染并有尺寸
    if (topProductsChart.value.clientWidth > 0 && topProductsChart.value.clientHeight > 0) {
      if (!topProductsChartInstance) {
        topProductsChartInstance = echarts.init(topProductsChart.value)
      }
      
      const option = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          top: '5%',
          left: 'center'
        },
        series: [
          {
            name: '产品数量',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: chartsData.topProducts
          }
        ]
      }
      
      topProductsChartInstance.setOption(option, true)
    }
  }
}

// 更新财务图表
const updateFinancialCharts = (chartsData: any) => {
  // 财务趋势折线图
  if (financialTrendChart.value) {
    // 确保DOM元素已渲染并有尺寸
    if (financialTrendChart.value.clientWidth > 0 && financialTrendChart.value.clientHeight > 0) {
      if (!financialTrendChartInstance) {
        financialTrendChartInstance = echarts.init(financialTrendChart.value)
      }
      
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['收入', '支出', '利润']
        },
        xAxis: {
          type: 'category',
          data: chartsData.financialTrend.map((item: any) => item.name)
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '收入',
            type: 'line',
            data: chartsData.financialTrend.map((item: any) => item.revenue),
            itemStyle: {
              color: '#67c23a'
            }
          },
          {
            name: '支出',
            type: 'line',
            data: chartsData.financialTrend.map((item: any) => item.expenses),
            itemStyle: {
              color: '#f56c6c'
            }
          },
          {
            name: '利润',
            type: 'line',
            data: chartsData.financialTrend.map((item: any) => item.profit),
            itemStyle: {
              color: '#409eff'
            }
          }
        ]
      }
      
      financialTrendChartInstance.setOption(option, true)
    }
  }
  
  // 支出分布饼图
  if (expenseDistributionChart.value) {
    // 确保DOM元素已渲染并有尺寸
    if (expenseDistributionChart.value.clientWidth > 0 && expenseDistributionChart.value.clientHeight > 0) {
      if (!expenseDistributionChartInstance) {
        expenseDistributionChartInstance = echarts.init(expenseDistributionChart.value)
      }
      
      const option = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          top: '5%',
          left: 'center'
        },
        series: [
          {
            name: '支出分布',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: chartsData.expenseDistribution
          }
        ]
      }
      
      expenseDistributionChartInstance.setOption(option, true)
    }
  }
}

// 添加供应商分析图表更新函数
const updateSupplierCharts = (chartsData: any) => {
  // 供应商分布柱状图
  if (supplierDistributionChart.value) {
    // 确保DOM元素已渲染并有尺寸
    if (supplierDistributionChart.value.clientWidth > 0 && supplierDistributionChart.value.clientHeight > 0) {
      if (!supplierDistributionChartInstance) {
        supplierDistributionChartInstance = echarts.init(supplierDistributionChart.value)
      }
      
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: chartsData.supplierDistribution.map((item: any) => item.name)
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '供应商数量',
            type: 'bar',
            data: chartsData.supplierDistribution.map((item: any) => item.value),
            itemStyle: {
              color: '#409eff'
            }
          }
        ]
      }
      
      supplierDistributionChartInstance.setOption(option, true)
    }
  }
  
  // 供应商状态堆叠柱状图
  if (supplierStatusChart.value) {
    // 确保DOM元素已渲染并有尺寸
    if (supplierStatusChart.value.clientWidth > 0 && supplierStatusChart.value.clientHeight > 0) {
      if (!supplierStatusChartInstance) {
        supplierStatusChartInstance = echarts.init(supplierStatusChart.value)
      }
      
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['合作中', '待审核', '已暂停', '已终止']
        },
        xAxis: {
          type: 'category',
          data: chartsData.supplierStatus.map((item: any) => item.name)
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '合作中',
            type: 'bar',
            stack: '总量',
            data: chartsData.supplierStatus.map((item: any) => item.active),
            itemStyle: {
              color: '#67c23a'
            }
          },
          {
            name: '待审核',
            type: 'bar',
            stack: '总量',
            data: chartsData.supplierStatus.map((item: any) => item.pending),
            itemStyle: {
              color: '#e6a23c'
            }
          },
          {
            name: '已暂停',
            type: 'bar',
            stack: '总量',
            data: chartsData.supplierStatus.map((item: any) => item.suspended),
            itemStyle: {
              color: '#909399'
            }
          },
          {
            name: '已终止',
            type: 'bar',
            stack: '总量',
            data: chartsData.supplierStatus.map((item: any) => item.terminated),
            itemStyle: {
              color: '#f56c6c'
            }
          }
        ]
      }
      
      supplierStatusChartInstance.setOption(option, true)
    }
  }
}

// 窗口大小调整处理
const handleResize = () => {
  if (customerDistributionChartInstance) {
    customerDistributionChartInstance.resize()
  }
  if (revenueTrendChartInstance) {
    revenueTrendChartInstance.resize()
  }
  if (salesTrendChartInstance) {
    salesTrendChartInstance.resize()
  }
  if (topProductsChartInstance) {
    topProductsChartInstance.resize()
  }
  if (financialTrendChartInstance) {
    financialTrendChartInstance.resize()
  }
  if (expenseDistributionChartInstance) {
    expenseDistributionChartInstance.resize()
  }
  if (supplierDistributionChartInstance) {
    supplierDistributionChartInstance.resize()
  }
  if (supplierStatusChartInstance) {
    supplierStatusChartInstance.resize()
  }
}

// 生命周期钩子
onMounted(() => {
  loadUserOrganizations()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  
  // 销毁图表实例
  if (customerDistributionChartInstance) {
    customerDistributionChartInstance.dispose()
  }
  if (revenueTrendChartInstance) {
    revenueTrendChartInstance.dispose()
  }
  if (salesTrendChartInstance) {
    salesTrendChartInstance.dispose()
  }
  if (topProductsChartInstance) {
    topProductsChartInstance.dispose()
  }
  if (financialTrendChartInstance) {
    financialTrendChartInstance.dispose()
  }
  if (expenseDistributionChartInstance) {
    expenseDistributionChartInstance.dispose()
  }
  if (supplierDistributionChartInstance) {
    supplierDistributionChartInstance.dispose()
  }
  if (supplierStatusChartInstance) {
    supplierStatusChartInstance.dispose()
  }
})
</script>

<style scoped>
.cross-organization-analysis {
  padding: 20px;
}

.org-selector-card {
  margin-bottom: 20px;
}

.org-selector {
  display: flex;
  align-items: center;
}

.analysis-results {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.analysis-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 18px;
  font-weight: 500;
}

.chart-container {
  width: 100%;
  height: 300px;
}

.loading-container,
.empty-container {
  padding: 50px 0;
  text-align: center;
}

@media (max-width: 768px) {
  .org-selector {
    flex-direction: column;
    gap: 15px;
  }
  
  .chart-container {
    height: 250px;
  }
}
</style>